package com.eeprint.common.utils;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * JSON解析处理
 *
 * @author Samven7
 * @date 2020/10/18 16:02
 */
public class JSON {
    private static final ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 对象转成json序列，并把结果输出成字符串
     * @param value 对象
     * @return 字符串
     * @throws Exception
     */
    public static String marshal(Object o) throws Exception {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonGenerationException e) {
            throw new Exception(e);
        } catch (JsonMappingException e) {
            throw new Exception(e);
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

    /**
     * 解析，字符串转为对象
     * @param str 字符串
     * @param valueType 对象类文件
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T unmarshal(String str, Class<T> valueType) throws Exception {
        try {
            return objectMapper.readValue(str, valueType);
        } catch (JsonParseException e) {
            throw new Exception(e);
        } catch (JsonMappingException e) {
            throw new Exception(e);
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

}
